﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinBookKeeping
{
    public partial class FrmAI : Form
    {
        public FrmAI()
        {
            InitializeComponent();
            InitializeHttpClient();
        }
        private void InitializeHttpClient()
        {
            _httpClient.BaseAddress = new Uri("https://api.deepseek.com");
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}");
        }
        private const string API_KEY = "sk-632491b75b8e4f7f817cbe24edeb5157";
        private readonly HttpClient _httpClient = new HttpClient();



        private async void confirm_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(send.Text))
                return;

            string userMessage = send.Text.Trim();
            AppendMessage("你", userMessage, Color.Blue);
            send.Clear();

            try
            {
                SetControlsEnabled(false);
                string aiResponse = await GetAIResponseAsync(userMessage);
                AppendMessage("AI助手", aiResponse, Color.Green);
            }
            catch (Exception ex)
            {
                AppendMessage("系统", $"出错: {ex.Message}", Color.Red);
            }
            finally
            {
                SetControlsEnabled(true);
                send.Focus();
            }
        }
        private async Task<string> GetAIResponseAsync(string userInput)
        {
            try
            {
                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = new[]
                    {
                        new { role = "system", content = "你是一个财务记账助手，用中文回答用户问题" },
                        new { role = "user", content = userInput }
                    },
                    temperature = 0.7,
                    max_tokens = 2000
                };

                var content = new StringContent(
                    JsonConvert.SerializeObject(requestBody),
                    Encoding.UTF8,
                    "application/json");

                var response = await _httpClient.PostAsync("/v1/chat/completions", content);
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync();
                dynamic responseData = JsonConvert.DeserializeObject(responseString);

                return responseData?.choices[0]?.message?.content?.ToString()?.Trim()
                    ?? "抱歉，我没有获取到有效的回复。";
            }
            catch (Exception ex)
            {
                return $"请求AI接口时出错: {ex.Message}";
            }
        }

        private void AppendMessage(string sender, string message, Color color)
        {
            answer.SelectionStart = answer.TextLength;
            answer.SelectionColor = color;
            answer.AppendText($"{sender}: {message}\n\n");
            answer.SelectionColor = answer.ForeColor;
            answer.ScrollToCaret();
        }

        private void SetControlsEnabled(bool enabled)
        {

            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Button)
                {
                    ctrl.Enabled = enabled;
                }
            }
            send.Enabled = enabled;
            Application.DoEvents();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            send.Clear();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
